/**
 * Created by 功振 on 2016/2/2.
 */
// 为了完善用户信息使用，将来会废弃掉
angular.module('Portal').controller('UpdateRegController', ["$rootScope", "$scope", "$state", "$cookies", "$interval", "userInfoService", function ($rootScope, $scope, $state, $cookies, $interval, userInfoService) {
    $scope.signUpInfo = true;

    var username = $cookies.get("username");
    if (username)
        $scope.username = username;
    if (!username)
        window.location.href = "/signin";
    else if ($cookies.get("hasPhone"))
        window.location.href = "/cp";

    $scope.phoneNumberRegex = "((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,2,3,5-9]))\\d{8}";
    $scope.idenCodeButtonContent = "获取手机验证码";
    $scope.isIdenCodeDisable = false;

    $rootScope.$broadcast('MainClassSet', 'reg_bg');


    $scope.triggerIdentifyingCode = function (phoneNumber) {
        userInfoService.triggerIdentifyingCode(phoneNumber).then(function (response) {
            countDown();
            return response;
        }, function(err) {
            alertify.alert('获取认证码错误', err.data);
        });
    }

    var countDown = function() {
        var timePromise = undefined;
        var second = 60;
        timePromise = $interval(function(){
            if(second <= 0){
                if (timePromise) {
                    $interval.cancel(timePromise);
                    timePromise = undefined;
                    second = 60;
                    $scope.idenCodeButtonContent = "获取手机验证码";
                    $scope.isIdenCodeDisable = false;
                }
            }else{
                $scope.idenCodeButtonContent = second + "秒后可重新获取";
                $scope.isIdenCodeDisable = true;
                second--;
            }
        }, 1000, 100);
    }

    $scope.ok = function () {

        if($scope.signUpForm.$valid){
            $scope.signUpInfo = false;
            $scope.isSignUping = true;

            var userInfo = {
                company: $scope.company,
                identifyingCode: $scope.identifyingCode,
                phoneNumber: $scope.phoneNumber
            }

            userInfoService.updateUser(userInfo).then(function(response){
                $scope.isSignUping = false;
                $scope.signUpSucceeded = true;
                //$cookies.put("username", $scope.username);
                $cookies.put("hasPhone", "1");
                window.location.href = "/cp";
                //$state.go("cp",{}, {reload:true});
            }, function(error){
                alertify.alert('update user error', error.data);
            });
        }else{
            alertify.alert('update user error', 'some error in submit form');
        }

    };
}]);